package com.trace.controller.report;


import com.trace.controller.report.rep.APIResult;
import com.trace.controller.report.vo.UserDepRespVO;
import com.trace.controller.report.vo.UserDepVO;
import com.trace.mapper.TUserMapper;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api")
public class UserController {
    @Resource
    private TUserMapper userMapper;

    @GetMapping("/user/tree")
    public APIResult getUserTree() {
        //这里需要排除掉自己
        List<UserDepVO> userDepVOS = userMapper.selectUserDep(1L);
        List<UserDepRespVO> respVOS = buildTree(userDepVOS);
        return APIResult.ok(respVOS);
    }

    public static List<UserDepRespVO> buildTree(List<UserDepVO> data) {
        Map<Integer, UserDepRespVO> departmentMap = new HashMap<>();
        List<UserDepRespVO> result = new ArrayList<>();

        for (UserDepVO entry : data) {
            // 检查部门是否已存在
            UserDepRespVO departmentNode = departmentMap.get(entry.getDeptId());
            if (departmentNode == null) {
                // 如果部门不存在，则创建部门节点
                departmentNode = new UserDepRespVO(entry.getDeptId(), entry.getDeptName());
                departmentMap.put(entry.getDeptId(), departmentNode);
                result.add(departmentNode);
            }

            // 添加用户到部门的 children
            if (departmentNode.getChildren() == null) {
                departmentNode.setChildren(new ArrayList<>());
            }
            departmentNode.getChildren().add(new UserDepRespVO(entry.getUserId(), entry.getUserName()));
        }

        return result;
    }
}
